<template>
  <div class="app-container">
    <!-- 搜索框 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="请输入关键字" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" clearable placeholder="状态">
            <el-option :value="1" label="未复核" />
            <el-option :value="2" label="已复核" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">
            重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button type="danger" :disabled="ids.length === 0 || queryParams.status === 2"
              @click="handleReCheck()"><i-ep-delete />批量复核</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="checkResultList" @selection-change="handleSelectionChange" border stripe
        style="width: 100%" highlight-current-row>
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" width="150" align="center">

          <template #default="{ $index }">
            {{ (queryParams.page - 1) * queryParams.limit + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="datasetName" width="300" header-align="center" align="center" label="数据集名称">
        </el-table-column>
        <el-table-column width="200" header-align="center" align="center" label="检测结果状态">

          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="warning">审核中</el-tag>
            <el-tag v-if="scope.row.status == 2" type="success">已复核</el-tag>
          </template>
        </el-table-column>
        <el-table-column width="200" header-align="center" align="center" label="通过率">

          <template #default="scope">
            {{ scope.row.passNums / scope.row.totalRuleNums * 100 }}%
          </template>
        </el-table-column>
        <el-table-column prop="totalRuleNums" width="200" header-align="center" align="center" label="总共规则数量">
        </el-table-column>
        <el-table-column prop="passNums" width="200" header-align="center" align="center" label="通过规则数量">
        </el-table-column>
        <el-table-column width="300" header-align="center" align="center" label="使用的规则">

          <template #default="scope">
            <!-- 显示规则，超链接方式 -->
            <el-button v-for="item in scope.row.ruleList" type="primary" @click="openRuleDetailDialog(item.id)" link>
              {{ item.name }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="gmtCreate" width="200" header-align="center" align="center" label="检测时间">
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="200" header-align="center" align="center">

          <template #default="scope">
            <el-button type="primary" round @click="openDialog(scope.row.contentUrl)"><i-ep-edit />检测内容</el-button>
            <el-button type="danger" :disabled="scope.row.status === 2" round
              @click="handleReCheck(scope.row.id)"><i-ep-delete />复核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-if="total > 0" :page-sizes="[5, 10, 15, 20]" v-model:total="total"
        v-model:page="queryParams.page" v-model:limit="queryParams.limit" @pagination="handleQuery"
        @size-change="sizeChangeHandle" @current-change="currentChangeHandle" />
    </el-card>


    <!-- 预览 -->
    <el-dialog v-model="preViewVisible" :width="'60%'">
      <!-- <preview ref="childRef" fileSuffix="txt" :imageSrc="textSrc" :key="dateKey"></preview> -->
      <el-alert
      style=" padding: 16px; background-color: #f0f7ff; border: 1px solid #c6e2ff; border-radius: 4px;"
       center type="success" :closable="false"
       class="custom-alert" 
       >
        <i class="el-icon-message"
          style="position: absolute; top: 16px; left: 16px; font-size: 20px; color: #409eff;"></i>
        <span class="custom-title-text" style="font-size: 18px; font-weight: 600; color: #409eff;">检测对话内容</span>
      </el-alert>
      <div class="serve_main" v-for="(item, index) in messageList" :key="index">
        <!-- 客服信息 -->
        <service v-if="isServer(item.name)" :name="item.name" :time="item.time" :avatar="sImg" :con="item.content"></service>
        <!-- 客户信息 -->
        <customer v-else :name="item.name" :time="item.time" :avatar="cImg" :con="item.content"></customer>
      </div>
    </el-dialog>

    <!-- 规则详情 -->
    <el-dialog v-model="ruleDetailViewVisible" :width="'90%'">
      <el-descriptions title="规则基本信息" direction="vertical" :column="3" border>
        <el-descriptions-item label="名称">{{ ruleDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="场景">{{ ruleDetail.scene }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ ruleDetail.bz }}</el-descriptions-item>
      </el-descriptions>
      <el-divider>
        <h3 style="color: blueviolet;"><strong>逻辑信息</strong></h3>
      </el-divider>
      <el-descriptions direction="vertical" :column="2" border>
        <el-descriptions-item label="条件间逻辑关系">{{ ruleDetail.content }}</el-descriptions-item>
      </el-descriptions>

      <el-divider>
        <h3 style="color: blueviolet;"><strong>条件列表</strong></h3>
      </el-divider>

      <el-table :data="ruleDetail.conditionList" border stripe style="width: 100%" highlight-current-row>
        <el-table-column label="条件编号" width="150" align="center">

          <template #default="{ $index }">
            条件{{ $index + 1 }}
          </template>
        </el-table-column>
        <!-- 显示算子列表 -->
        <el-table-column type="expand" stripe label="算子列表" width="300">

          <template #default="props">
            <h3>算子列表</h3>
            <el-table :data="props.row.operatorList">
              <el-table-column label="算子编号" width="100">
                <template #default="{ $index }">
                  算子{{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="类型" prop="type" width="150">

                <template #default="scope">
                  <el-tag v-if="scope.row.type == 1" type="warning">正则表达式</el-tag>
                  <el-tag v-if="scope.row.type == 2" type="success">包含关键词</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="内容" prop="content" width="100" />
            </el-table>
          </template>

        </el-table-column>
        <el-table-column prop="content" width="300" header-align="center" align="center" label="算子间逻辑关系">
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">

import {
  getCheckListApi,
  reCheckApi,
  getInfoApi,
} from "@/api/qualityInspect/rule.js";
import { reactive, ref } from "vue";
import preview from '@/components/Preview/index.vue'
import service from "@/views/qualityInspect/service.vue"
import customer from "@/views/qualityInspect/customer.vue"
import axios from "axios";
import {
  ElForm,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElTable,
} from 'element-plus'

import sImg from '@/assets/images/fileImg/客服图片.jpg'
import cImg from '@/assets/images/fileImg/客户图片.jpg' 


// 分页查询参数接口
interface KeywordQuery {
  keywords?: string;
  page?: number;
  limit?: number;
  status?: number;
}

const preViewVisible = ref(false)
const ruleDetailViewVisible = ref(false)
const textSrc = ref('')
const queryFormRef = ref(ElForm); // 查询表单
const loading = ref(false);
const ids = ref([]); // 被选中的id集合
const total = ref(0);
const queryParams = reactive<KeywordQuery>({
  page: 1,
  limit: 10,
  status: 1,
});

const checkResultList = ref<[]>();
const ruleDetail = ref({
  conditionList: []
});
const childRef = ref();
const dateKey = ref();
const messageList = ref<[]>();

/**
 * 判断是否为客服
 */
const isServer = (name)=>{
  const regex = /^客服\d+$/;
  return regex.test(name);
} 

/**
 * 查询
 */
const handleQuery = () => {
  loading.value = true;
  getCheckListApi(queryParams) // 获取列表
    .then(({ data }) => {
      checkResultList.value = data.list;
      total.value = data.totalCount;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  queryParams.status = 1;
  handleQuery();
}

/**
 * 修改每页数
 */
const sizeChangeHandle = (val: number) => {
  queryParams.limit = val
  queryParams.page = 1
  handleQuery()
}

/**
 * 修改当前页
 */
const currentChangeHandle = (val: number) => {
  queryParams.page = val
  handleQuery()
}

/**
 * 行checkbox change事件
 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
}


/**
 * 打开检查结果文本弹窗
 */
const openDialog = (src?: string) => {
  // 获取信息体
  axios.get(src, {
            responseType: "json",
        }).then(res => {
          messageList.value = JSON.parse(JSON.stringify(res.data)); 
        })

  preViewVisible.value = true
}

/**
 * 打开规则详情弹窗
 */
const openRuleDetailDialog = (id?: number) => {

  // 获取规则详情
  getInfoApi(id).then(({ data }) => {
    ruleDetail.value = data
  })

  ruleDetailViewVisible.value = true

}



/**
 * 复核
 */
const handleReCheck = (id?: number) => {
  let resultIds = []
  // 单个复核
  if (id != null) {
    resultIds.push(id)
  } else {
    // 批量复核
    if (!ids) {
      ElMessage.warning("请勾选复核项");
      return;
    }
    resultIds = ids.value
  }


  ElMessageBox.confirm("确认复核选中的记录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    reCheckApi(resultIds).then(() => {
      ElMessage.success("复核成功");
      resetQuery();
    });
  });
}


handleQuery(); // 初始化列表数据

</script>
<style scoped>
.serve_main {
  padding: 10px 20px;
}
.custom-alert {  
  display: flex;  
  align-items: center;  
  justify-content: center;  
}  
  
.custom-alert .el-alert__title {  
  flex: 1; /* 让标题填满剩余空间 */  
  text-align: center; /* 确保标题文本居中 */  
  font-size: 18px;  
  font-weight: 600;  
  color: #409eff;  
}  
  
/* 如果需要，可以添加图标样式 */  
.custom-alert .el-icon-message {  
  margin-right: 8px; /* 与标题文本保持适当的间距 */  
}  
</style>
